import {
  getOrderList, cancelOrder, buy, confirmDelivery,
  confirmReturn, payOrder, renewal, getSettlem
} from '../../services/order'
import {
  ONE_DAY,
  dateFormat,
  getStartAndEndDate,
} from '../../utils/date'
import { 
  ORDER_STATE_NAME_ARR,
  DEPOSIT_STATE_NAME_ARR,
} from '../../services/const'

// 订单操作类型标识
const OPERATE_TYPE_DICT = {
  LOOKDELIVERY: 'isCanLookDelivery',        // 查看物流
  BACK: 'isCanBack',                        // 归还设备
  LOOKSETTLE: 'isCanLookSettle',            // 查看账单
  BUYOUT: 'isCanBuyOut',                    // 买断设备
  RELET: 'isCanRelet',                      // 续租设备
  LOOKSTAGE: 'isCanLookStage',              // 查看分期
  CONFIRMDELIVERY: 'isCanconfirmDelivery',  // 确认收货
  CANCEL: 'isCanCancel',                    // 取消订单  
  PAY: 'isCanPay',                          // 支付订单
}

const OPERATE_TYPE_NAME_MAP = { 
  [OPERATE_TYPE_DICT.LOOKDELIVERY]: '查看物流', 
  [OPERATE_TYPE_DICT.BACK]: '归还设备', 
  [OPERATE_TYPE_DICT.LOOKSETTLE]: '查看账单' ,
  [OPERATE_TYPE_DICT.BUYOUT]: '买断设备', 
  [OPERATE_TYPE_DICT.RELET]: '续租设备', 
  [OPERATE_TYPE_DICT.LOOKSTAGE]: '查看分期', 
  [OPERATE_TYPE_DICT.CONFIRMDELIVERY]: '确认收货' ,
  [OPERATE_TYPE_DICT.CANCEL]: '取消订单',
  [OPERATE_TYPE_DICT.PAY]: '支付订单',
}

Page({
  data: {
    OPERATE_TYPE_DICT,
    OPERATE_TYPE_NAME_MAP,
    OPERATE_TYPE_KEY_ARR: Object.keys(OPERATE_TYPE_DICT),

    tabs: [
      { state: 10, title: '待支付' }, 
      { state: -1, title: '全部' },
      ...[0,1,2,4,5,6,7].map(state => ({ state, title: ORDER_STATE_NAME_ARR[state] })),
    ],

    expressModalOpened: false,
    settleModalOpened: false,
    returnExpressNo: '',
    returnExpressName: '',
    lostMoney: '',
    damageMoney: '',
    violateMoney: '',
    totalMoney: '',
    settleRemark: '',

    page: 1, // 当前页数
    isEnd: false,
    list: [], // 页面List数据
  
    activeIndex: 0,
    orderStatus: -1,
    orderId: 0,
    activeOperateType: '',
  },
  onLoad({ orderStatus = -1 }) {
    const { tabs } = this.data

    my.setNavigationBar({
      title: '我的订单',
      backgroundColor: '#4BA3F9'
    })

    this.setData({ orderStatus, activeIndex: tabs.findIndex(item => item.state == orderStatus) })
    this.getOrderList()

    this.operationMap = {
      [OPERATE_TYPE_DICT.LOOKDELIVERY]: '查看物流', 
      [OPERATE_TYPE_DICT.BACK]: '归还设备', 
      [OPERATE_TYPE_DICT.LOOKSETTLE]: '查看账单' ,
      [OPERATE_TYPE_DICT.BUYOUT]: '买断设备', 
      [OPERATE_TYPE_DICT.RELET]: '续租设备', 
      [OPERATE_TYPE_DICT.LOOKSTAGE]: '查看分期', 
      [OPERATE_TYPE_DICT.CONFIRMDELIVERY]: '确认收货' ,
      [OPERATE_TYPE_DICT.CANCEL]: this.cancelOrder,
      [OPERATE_TYPE_DICT.PAY]: this.payDespositOrder,
    }
  },
  handleTabClick({ index }) {
    this.setData({ activeIndex: index, orderStatus: this.data.tabs[index].state })
    my.startPullDownRefresh()
  },
  handleOperation({ target: { dataset: { id, type, index } } }) {
    this.operationMap[type] && this.operationMap[type].bind(this)(id, index)
  },
  onPullDownRefresh() {
    let that = this
    this.setData({
      list: [],
      page: 1,
      pages: 1
    });
    setTimeout(function () {
      that.getOrderList()
    }, 1000)
  },
  stopPullDownRefresh() {
    my.stopPullDownRefresh({
      complete(res) {
        console.log(res, new Date())
      }
    })
  },
  async getOrderList() {
    const { page, orderStatus, list } = this.data

    const { code, data } = await getOrderList({
      page_num: page,
      type: orderStatus
    })

    this.stopPullDownRefresh()

    if (code !== 0) {
      return false
    }

    let orderList = []
    if (orderStatus === 10) {
      orderList = this.formateDepositOrder(data.list)
    } else if (orderStatus === 11) {
      orderList = this.formateRefundOrder(data.list)
    } else {
      orderList = this.formateNormalOrder(data.list)
    }
    console.log('orderList', orderList)
    this.setData({
      list: page === 1 ? orderList : list.concat(orderList),
      isEnd: data.list.length < 5, 
      page: page + 1,
    })
  },
  formateRefundOrder() {
    // rental模式没有
  },
  formateNormalOrder(list) {
    const isRental = (getApp()).globalData.playforminfo.mode

    return list.map(element => {
      element.orderStatusName = ORDER_STATE_NAME_ARR[element.state]

      element[OPERATE_TYPE_DICT.LOOKDELIVERY] = element.state >= 2 && element.state != 3
      element[OPERATE_TYPE_DICT.BACK] = isRental && element.state === 4 ? true : false
      element[OPERATE_TYPE_DICT.LOOKSETTLE] = element.state > 5
      element[OPERATE_TYPE_DICT.BUYOUT] = false
      element[OPERATE_TYPE_DICT.RELET] = false
      element[OPERATE_TYPE_DICT.LOOKSTAGE] = false
      element[OPERATE_TYPE_DICT.CONFIRMDELIVERY] = false
      element[OPERATE_TYPE_DICT.CANCEL] = false
      element[OPERATE_TYPE_DICT.PAY] = false

      const [ rentStart, rentEnd ] = 
        element.state >= 4 ? 
        getStartAndEndDate(element.receive_time, element.rent_time) : 
        getStartAndEndDate(+new Date(element.create_time) + ONE_DAY * 2, element.rent_time)

      element.rentStart = rentStart
      element.rentEnd = rentEnd

      return element
    })
  },
  formateDepositOrder(list) {
    return list.map(element => {
      const [ rentStart, rentEnd ] = getStartAndEndDate(+new Date(element.create_time) + ONE_DAY * 2, element.rent_time)
      const depositState = element.deposit_info.state

      return {
        ...element,
        rentStart,
        rentEnd,
        state: depositState,
        orderStatusName: DEPOSIT_STATE_NAME_ARR[depositState],
        [OPERATE_TYPE_DICT.CANCEL]: depositState === 1,
        [OPERATE_TYPE_DICT.PAY]: depositState === 1,
      }
    })
  },
  async scrollMytrip() {
    if (!this.data.isEnd) {
      this.setData({ page: this.data.page + 1 });
      this.getOrderList();
    }
  },
  toCustomService() {
    my.switchTab({
      url: '/pages/customer/customer',
    })
  },
  todetail(event) {
    my.navigateTo({
      url: '/pages/orderDetail/orderDetail?orderId=' + event.target.dataset.id,
    })
  },
  confirmDelivery(event) {
    my.confirm({
      title: '温馨提示',
      content: '确定收货吗?',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      success: (result) => {
        if (result.confirm) {
          confirmDelivery({ orderId: event.target.dataset.id }).then(res => {
            if (res.code == 0) {
              my.startPullDownRefresh()
            }
          })
        }
      },
    });
  },
  notAuthorizedApply({ target: { dataset: { id, type } } }) {
    const { OPERATE_TYPE_NAME_MAP } = this.data
    my.confirm({
      title: '温馨提示',
      content: '当前订单商品无法' + OPERATE_TYPE_NAME_MAP[type],
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      success: (result) => {
        if (result.confirm) {}
      }
    })
  },
  openModal({ target: { dataset: { id, type } } }) {
    this.setData({
      expressModalOpened: true,
      returnExpressName: '',
      returnExpressNo: '',
      orderId: id,
      activeOperateType: type,
    });
  },
  onItemInput(e) {

    this.setData({

      [e.target.dataset.field]: e.detail.value,

    });
  },
  onClear(e) {

    this.setData({

      [e.target.dataset.field]: '',

    });
  },
  onModalClose2() {
    this.setData({
      settleModalOpened: false,
    });
  },
  onModalClose() {
    this.setData({
      expressModalOpened: false,
    });
  },
  looksettle(event) {
    getSettle({ orderId: event.target.dataset.id }).then(res => {
      if (res.code == "000000") {
        this.setData({
          settleModalOpened: true,
          lostMoney: res.data.lostMoney,
          violateMoney: res.data.violateMoney,
          totalMoney: res.data.totalMoney,
          damageMoney: res.data.damageMoney,
          settleRemark: res.data.settleRemark
          ,
          orderId: event.target.dataset.id
        });
      }
    })
  },
  backorder() {
    if (this.data.returnExpressNo.length <= 0) {
      my.showToast({
        type: 'fail',
        content: '请填写快递单号',
        duration: 2000,
      });
      return
    }
    if (this.data.returnExpressName.length <= 0) {
      my.showToast({
        type: 'fail',
        content: '请填写快递名称',
        duration: 2000,
      });
      return
    }

    confirmReturn({
      orderId: this.data.orderId,
      returnExpressName: this.data.returnExpressName,
      returnExpressNo: this.data.returnExpressNo
    }).then(res => {
      if (res.code == "000000") {
        this.onModalClose()
        my.startPullDownRefresh()
      }
    })
  },
  lookdelivery(event) {
  },
  onpayOrder(orderID, data) {
    if (data.payType == 0) {
      my.showToast({
        type: 'fail',
        content: data.payData,
        duration: 2000,
      });
      return
    } else if (data.payType == 1) {
      my.tradePay({
        tradeNO: data.payData,
        success: function (ret) {
          if (ret.resultCode == 9000) {
            my.showToast({
              type: 'success',
              content: '支付成功',
            })

            my.startPullDownRefresh()
          } else {
            my.showToast({
              type: 'fail',
              content: '支付失败',
              duration: 2000,
            })
          }
        },
        fail: function (res) {
          console.log(res)
        },
      })
    }
  },
  async cancelOrder(id, index) {
    my.showLoading()
    const { code, data } = await cancelOrder({ orderId: id })
    my.hideLoading()
    
    if (code != 0) { return false }

    my.showToast({
      type: 'success',
      content: '取消成功，预冻结押金将在1个工作日内解冻',
      duration: 3000,
    })

    const { list } = this.data
    list[index].state = 3
    list[index].orderStatusName = DEPOSIT_STATE_NAME_ARR[3]
    list[index][OPERATE_TYPE_DICT.CANCEL] = false
    list[index][OPERATE_TYPE_DICT.PAY] = false
    
    this.setData({ list })
  },
  async payDespositOrder(id, index) {
    const { code, data } = await payOrder({ preOrderId: id })
    if (code !== 0) { return false }

    const that = this

    my.tradePay({
      tradeNO: data.payParams.tradeNo,
      success: function (resultAli) {
        if (resultAli.resultCode == 9000) {
          my.showToast({
            type: 'success',
            content: '支付成功',
            duration: 2000,
          })

          const { list } = that.data
          list[index].state = 0
          list[index].orderStatusName = ORDER_STATE_NAME_ARR[0]
          list[index][OPERATE_TYPE_DICT.CANCEL] = false
          list[index][OPERATE_TYPE_DICT.PAY] = false
          
          that.setData({ list })
        } else {
          my.showToast({
            type: 'fail',
            content: '支付失败 请重试',
            duration: 2000,
          })
        }
      },
      fail: function (res) {
        my.showToast({ type: 'fail', content: '支付服务异常 请退出重试' })
      },
    })
  },
})


